<!--
 * @Author: your name
 * @Date: 2021-08-17 10:26:04
 * @LastEditTime: 2021-08-23 21:13:08
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \orderSystems\src\components\gou\DishUinitTable.vue
-->
<template>
  <!-- 菜品单位复用组件 -->
  <div id="dish-table">
    <!-- 表格title -->
    <el-container>
      <el-header class="table-header">
        <div class="table-title">
          <el-row class="title-row">
            <el-col :span="18">{{ moudleName }}</el-col>
            <el-col :span="6">
              <el-button
                class="btn-size"
                type="primary"
                icon="el-icon-circle-plus-outline"
                @click="dialogFormVisible = true"
                >新增</el-button
              >
              <el-button
                class="btn-size"
                type="danger"
                icon="el-icon-delete"
                @click="batchDelete"
                >批量删除</el-button
              >
            </el-col>
            <el-dialog
              title="新增"
              :visible.sync="dialogFormVisible"
              center
              width="30%"
              top="30vh"
            >
              <el-form :model="form">
                <el-form-item label="单位名称:" :label-width="formLabelWidth">
                  <el-input clearable v-model="form.name" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="备注:" :label-width="formLabelWidth">
                  <el-input
                    clearable
                    v-model="form.remarks"
                    type="textarea"
                    :rows="4"
                    autocomplete="off"
                  ></el-input>
                </el-form-item>
                <el-form-item label="状态" :label-width="formLabelWidth">
                  <el-switch
                    v-model="form.status"
                    active-color="#13ce66"
                    inactive-color="#9E99B9"
                  >
                  </el-switch>
                </el-form-item>
              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button @click="cancelAdd">取 消</el-button>
                <el-button type="primary" @click="defineAdd">确 定</el-button>
              </div>
            </el-dialog>
          </el-row>
        </div>
      </el-header>
    </el-container>
    <!-- 表格数据 -->
    <el-container>
      <el-main class="table-content">
        <div class="table-bgc">
          <div class="table-padding">
            <el-table
              ref="multipleTable"
              :data="tableDatas"
              tooltip-effect="dark"
              border
              @selection-change="handleSelectionChange"
              class="table-box"
            >
              <el-table-column type="selection" width="55" align="center">
              </el-table-column>
              <el-table-column label="序号" width="120" align="center">
                <template slot-scope="scope">{{ scope.$index + 1 }}</template>
              </el-table-column>
              <el-table-column label="单位名称" width="150" align="center">
                <template slot-scope="scope">{{ scope.row.unit }}</template>
              </el-table-column>
              <el-table-column label="备注" align="center">
                <template slot-scope="scope">{{ scope.row.notes }}</template>
              </el-table-column>
              <el-table-column label="状态" width="240" align="center">
                <template slot-scope="scope">{{
                  scope.row.status == 0 ? "正常" : "待开发"
                }}</template>
              </el-table-column>
              <el-table-column label="操作" width="240" align="center">
                <template slot-scope="scope">
                  <el-button
                    type="danger"
                    size="mini"
                    plain
                    @click="handleEdit(scope.row.id)"
                    icon="el-icon-edit"
                    >编辑</el-button
                  >
                  <el-button
                    size="mini"
                    type="warning"
                    plain
                    @click="handleDelete(scope.row.id)"
                    icon="el-icon-delete"
                    >删除</el-button
                  >
                  <el-dialog
                    title="编辑"
                    :visible.sync="dialogFormVisible1"
                    center
                    width="30%"
                    top="30vh"
                  >
                    <el-form :model="editForm">
                      <el-form-item
                        label="类别名称:"
                        :label-width="formLabelWidth"
                      >
                        <el-input
                          v-model="editForm.unit"
                          autocomplete="off"
                        ></el-input>
                      </el-form-item>
                      <el-form-item label="备注:" :label-width="formLabelWidth">
                        <el-input
                          v-model="editForm.notes"
                          type="textarea"
                          :rows="4"
                          autocomplete="off"
                        ></el-input>
                      </el-form-item>
                      <el-form-item label="状态" :label-width="formLabelWidth">
                        <el-switch
                          v-model="editForm.status"
                          active-color="#13ce66"
                          inactive-color="#9E99B9"
                        >
                        </el-switch>
                      </el-form-item>
                    </el-form>
                    <div slot="footer" class="dialog-footer">
                      <el-button @click="cancelEdit">取 消</el-button>
                      <el-button type="primary" @click="defineEdit"
                        >确 定</el-button
                      >
                    </div>
                  </el-dialog>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script>
export default {
  data() {
    return {
      /* tableData: [
       {
          order: "001",//序号
          category: "个",
          remarks:'',
          status:'正常',
        },
        {
          order: "001",//序号
          category: "盘",
          remarks:'',
          status:'正常',
        },
        {
          order: "001",//序号
          category: "只",
          remarks:'',
          status:'正常',
        },
        {
          order: "001",//序号
          category: "个",
          remarks:'',
          status:'正常',
        },
        {
          order: "001",//序号
          category: "盘",
          remarks:'',
          status:'正常',
        },
      ], */
      multipleSelection: [],
      // dialogTableVisible: false,
      dialogFormVisible: false,
      dialogFormVisible1: false,
      nowPageDataAll: 0, //当前点击页的数据条数
      nowPage: 0, //当前点击页
      dishId: 0, //点击编辑行数据的id
      form: {
        name: "", //名字
        remarks: "", //备注
        status: "false",
      },
      editForm: {
        //对话框弹窗相应的数据对象
        unit: "", //类别名称
        notes: "", //备注
        status: "false", //状态
      },
      formLabelWidth: "80px",
    };
  },
  props: {
    moudleName: {
      //模块名字
      type: String,
      default: "",
    },
    tableDatas: {
      //从父组件接收表格数据
      type: Array,
    },
    clickNowPage: {
      //当前页，从父级接收
      default: 1,
      type: Number,
    },
    pageCount: {
      //每页显示数据条数，从父级接收
      default: 5,
      type: Number,
    },
    nowPageSize: {
      //当前点击页的数据条数
      default: 0,
      type: Number,
    },
  },

  methods: {
    /**
     * @description: 添加菜品单位函数
     * @param {*}
     * @return {*}
     */
    async defineAdd() {
      this.dialogFormVisible = false; //关闭弹框
      const { data: res } = await this.axios.post("/dishUnit/add", {
        unit: this.form.name, //菜品类别变量
        notes: this.form.remarks, //备注
        status: this.form.status ? 0 : 1, //0 表示正常 1表示待开发
      });
      if (res.code == 200) {
        this.$message({
          message: "添加成功！",
          type: "success",
          duration: "500",
        });
        this.$emit("shareData", {
          nowPage: this.clickNowPage,
          pageCount: this.pageCount,
        });
      } else {
        throw new console.error("服务器错误");
      }
    },
    /**
     * @description:添加对话框弹窗点击取消时隐藏对话框
     * @param {*}
     * @return {*}
     */
    cancelAdd() {
      this.dialogFormVisible = false;
      this.$message({
        message: "取消添加！",
        type: "info",
        duration: "500",
      });
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    /**
     * @description: 获取选中行的表格数据的id数组，用于批量删除
     * @param {*} val //选中的数据数组
     * @return {*}
     */
    handleSelectionChange(val) {
      //val获取选中的数据数组
      let idArr = []; //用于存储表格每行数据的id的数据
      val.forEach((item) => {
        //遍历数组，获取每条数据的id,
        idArr.push(item.id); //将id存储到新数组中
      });
      this.multipleSelection = idArr; //将新数组的值赋值给data中定义的数组
    },
    /**
     * @description: 用于批量删除的函数
     * @param {*}
     * @return {*}
     */
    async batchDelete() {
      const confirm = await this.$confirm(
        //this.$fonfirm是一个promise对象，因此用async await
        "此操作将永久删除选中数据, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err); //点击确认，返回confirm 点击取消，返回 cancel
      if (confirm != "confirm") {
        //如果不是点击确认，表示不删除
        this.$message({
          type: "info",
          message: "已取消删除",
          duration: "500",
        });
      } else {
        const { data: res } = await this.axios.post("/dishUnit/deleteIds", {
          ids: this.multipleSelection, //删除数据的id数组
        });
        if (res.code == 200) {
          // console.log(res);
          this.$message({
            type: "success",
            message: "删除成功!",
            duration: "500",
          });
          this.nowPageDataAll = this.nowPageSize - 1; //data里面定义的当前页数据-1后的值
          if (this.nowPageDataAll == 0) {
            //当前页数据删完时
            this.nowPage = this.clickNowPage; //首先讲props中的当前页页面赋值给data中的当前页页面
            this.nowPage = this.nowPage - 1; //页码-1,回到上一页
            if (this.nowPage <= 0) {
              this.nowPage = 1; //只有一页时就在第一页
            }
          } else {
            this.nowPage = this.clickNowPage; //当前页没删完时，就在当前页
          }
          this.$emit("shareData", {
            //子传父自定义事件
            nowPage: this.nowPage,
            pageCount: this.pageCount,
          });
        } else {
          throw new console.error("删除失败");
        }
      }
    },
    /* *
     * @description: 获取表格某一行数据的id和数据
     * @param {*} id  编辑行数据的id
     * @return {*}
     */
    async handleEdit(id) {
      this.dialogFormVisible1 = true; //修改变量值，弹出弹框
      this.dishId = id;
      const { data: res } = await this.axios.get("/dishUnit/findById/" + id);
      if (res.code == 200) {
        this.editForm = res.data; //将值赋值给编辑弹窗，显示编辑的元素数据
        this.editForm.status = this.editForm.status == 0 ? true : false; //0 打开 1关闭
      }
    },
    /**
     * @description: 取消编辑函数
     * @param {*}
     * @return {*}
     */
    cancelEdit() {
      this.dialogFormVisible1 = false;
      this.$message({
        type: "info",
        message: "取消修改！",
        duration: "500",
      });
    },
    /**
     * @description: 点击编辑弹框的确认按钮，修改菜品单位一行数据
     * @param {*}
     * @return {*}
     */
    async defineEdit() {
      const { data: res } = await this.axios.post("/dishUnit/update", {
        id: this.dishId,
        notes: this.editForm.notes,
        status: this.editForm.status ? 0 : 1,
        unit: this.editForm.unit,
      });
      console.log(res);
      if (res.code == 200) {
        this.$message({
          message: "编辑成功！",
          type: "success",
          duration: "500",
        });
        this.dialogFormVisible1 = false; //点击确定，关闭对话框
        this.$emit("shareData", {
          nowPage: this.clickNowPage,
          pageCount: this.pageCount,
        });
      } else {
        throw new console.error("修改失败");
      }
    },
    /**
     * @description: 根据id删除表格一行数据的函数
     * @param {*} id  当前删除行数据的id
     * @return {*}
     */
    async handleDelete(id) {
      // console.log(id);
      const confirm = await this.$confirm(
        //this.$fonfirm是一个promise对象，因此用async await
        "此操作将永久删除该数据, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err); //点击确认，返回confirm 点击取消，返回 cancel
      if (confirm != "confirm") {
        //如果不是点击确认，表示不删除
        this.$message({
          type: "info",
          message: "已取消删除",
          duration: "500",
        });
      } else {
        //确认删除时发起ajax请求，删除数据
        this.axios
          .get("/dishUnit/delete/" + id)
          .then((res) => {
            //  console.log(res);
            if (res.data.code == 200) {
              this.$message({
                type: "success",
                message: "删除成功!",
                duration: "500",
              }); //后面将props值赋值给data中的相应值再修改，主要是因为pros中的值不能修改
              this.nowPageDataAll = this.nowPageSize - 1; //data里面定义的当前页数据-1后的值
              if (this.nowPageDataAll == 0) {
                //当前页数据删完时
                this.nowPage = this.clickNowPage; //首先讲props中的当前页页面赋值给data中的当前页页面
                this.nowPage = this.nowPage - 1; //页码-1,回到上一页
                if (this.nowPage <= 0) {
                  this.nowPage = 1; //只有一页时就在第一页
                }
              } else {
                this.nowPage = this.clickNowPage; //当前页没删完时，就在当前页
              }
              this.$emit("shareData", {
                //子传父自定义事件
                nowPage: this.nowPage,
                pageCount: this.pageCount,
              });
            }
          })
          .catch((err) => err);
      }
    },
  },
};
</script>

<style lang='less' scoped>
.table-header {
  padding: 0;
  & > .table-title {
    margin: 1rem;
    background-color: #f5f9fc;
    box-sizing: border-box;
    height: 4rem;
    & > .title-row {
      line-height: 4rem;
      padding-left: 1rem;
      color: #666;
      font-weight: 500;
    }
  }
}
.btn-size {
  height: 3rem;
  padding: 0.6rem 2rem;
}

.table-content {
  padding: 0;
  & > .table-bgc {
    margin: 0 1rem 1rem;
    background-color: #f5f9fc;
    // height: 50rem;
    overflow: hidden;
    box-sizing: border-box;
    & > .table-padding {
      margin: 1rem;
    }
  }
}
</style>
